import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';

//声明state的接口
export interface IndexModelState {
  isLogin: boolean;
}

//当前model的接口
export interface IndexModelType {
  namespace: 'login';
  state: IndexModelState;
  effects: {
    change: Effect;
  };
  reducers: {
    // save: Reducer<IndexModelState>;
    // 启用 immer 之后
    save: ImmerReducer<IndexModelState>;
  };
  subscriptions: { setup: Subscription };
}

const IndexModel: IndexModelType = {
  namespace: 'login', //命名空间

  state: {           //状态
    name: 'lixd',
  },
  //actions  generator语法  function * fun(){ yiled }
  effects: {        //异步请求和业务逻辑
    *change({ payload }, { call, put }) {
        console.log("=====effect",payload)
        //payload 参数  call 调用接口  put(type:reducer对应的函数名,参数) 派发reducer
        yield put({
            type:'save',
            payload
        })
    },
  },
  //mutations
  reducers: {       //修改state
    // save(state, action) {
    //     console.log("===")
    //     return {
    //         ...state,
    //         ...action.payload
    //     };
    // },
    // 启用 immer 之后
    save(state, action) {
      state.name = action.payload.name;
    },
  },
//   subscriptions: {
//     setup({ dispatch, history }) {
//       return history.listen(({ pathname }) => {
//         if (pathname === '/login') {
//           dispatch({
//             type: 'change',
//             payload:{name:'lili'}
//           })
//         }
//       });
//     }
//   }
};

export default IndexModel;